import re

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    return {
        "token":token,
        "username":user.username,
        "user_id":user.id,
    }




def get_user_by_account(username):
    try:
        if re.match(r'1[3-9]\d{9}', username):
            # 手机号
            user = User.objects.get(mobile=username)
        else:
            # 用户名
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        user = None


    return user



#重写登录用户名方法   系统只用户名  实际上可以用用户名或在手机号都可以
from django.contrib.auth.backends import ModelBackend

class UsernameMobileModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 1. 根据正则来判断 用户的 username 是手机号还是 用户名
        # username =  18310820688
        # User.objects.get(mobile=)

        # username =  itheima
        # User.objects.get(username=)
        # try:
        #     if re.match(r'1[3-9]\d{9}',username):
        #         #手机号
        #         user = User.objects.get(mobile=username)
        #     else:
        #         #用户名
        #         user = User.objects.get(username=username)
        # except User.DoesNotExist:
        #     user = None
        user = get_user_by_account(username)
        # 2. 根据user进行校验
        if user is not None and user.check_password(password):
            return user

        return None
